use crate::config::create_settings_service;
use reqwest::header::{HeaderMap, ACCEPT};
use reqwest::Client;
use serde_json::Value;

pub async fn get_urls(base_url: &str) -> Vec<String> {
    let mut urls = Vec::new();

    let client = Client::new();
    let settings_service = create_settings_service();

    // 获取 server_address
    let server_address = match settings_service.get_setting("server_address") {
        Ok(Some(value)) => value,
        Ok(None) => {
            println!("Setting not found");
            return urls;
        }
        Err(e) => {
            println!("Error occurred: {}", e);
            return urls;
        }
    };

    let link_application = match settings_service.get_setting("link_application") {
        Ok(Some(value)) => value,
        Ok(None) => "1000".to_string(),
        Err(e) => {
            println!("Error occurred: {}", e);
            return urls;
        }
    };

    let link_application_num = link_application.parse::<u32>().unwrap();

    let count = link_application_num / 100;
    for _ in 0..count {
        // 休息0.1秒
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        // 构建完整 URL
        let full_url = format!("{}/api/goods/?base_url={}", &server_address, base_url);

        // 设置请求头
        let mut headers = HeaderMap::new();
        headers.insert(
            ACCEPT,
            reqwest::header::HeaderValue::from_static("application/json"),
        );

        // 发送请求
        let response = match client.get(&full_url).headers(headers).send().await {
            Ok(response) => response,
            Err(err) => {
                eprintln!("Request error: {}", err);
                return urls;
            }
        };

        // 检查响应状态码
        if !response.status().is_success() {
            eprintln!("Failed to fetch data: {}", response.status());
            return urls;
        }

        // 解析 JSON 响应
        let json: Value = match response.json().await {
            Ok(json) => json,
            Err(err) => {
                eprintln!("Failed to parse JSON: {}", err);
                return urls;
            }
        };

        // 处理 JSON 数据
        if let Value::Array(array) = json {
            // 判断 JSON 数组长度是否大于 0
            if array.len() == 0 {
                return urls;
            }
            for element in array {
                if let Value::String(s) = element {
                    urls.push(s);
                } else {
                    eprintln!("Response JSON element is not a string");
                    break;
                }
            }
            println!("Response JSON: {:?}", urls);
        } else {
            println!("Response JSON is not an array");
        }
    }

    urls
}
